<?php

namespace api\modules\v1\controllers;

use api\common\controllers\ApiController;

use yii\filters\AccessControl;
use backend\models\Check;
use backend\models\Goods;
use backend\models\Message;
use yii;
use api\modules\v1\models\LoginForm;
use api\modules\v1\models\AdminUser;
use yii\base\DynamicModel;

/**
 * Public controller for the `user` module
 */
class GoodsController extends ApiController
{


    //购买物资

    public function actionPurchase()
    {
        $request = Yii::$app->request;
        $postData = $request->post();

        if(empty($postData['name'] ) || empty($postData['model'] ) || empty($postData['unit']) || empty($postData['price']) || empty($postData['request_num']) || empty($postData['all_price']) || empty($postData['buy_time']) || empty($postData['image'])){
          return parent::isMessage(400,'参数不能为空');
        }else{
            $purchase = new Check();
            $purchase['pid']       = Yii::$app->user->identity->getId();
            $purchase['name']      = $postData['name'];
            $purchase['model']     = $postData['model'];
            $purchase['unit']      = $postData['unit'];
            $purchase['request_num'] = $postData['request_num'];
            $purchase['price']     = $postData['price'];
            $purchase['all_price'] = $postData['all_price'];
            $purchase['buy_time']  = $postData['buy_time'];
            $purchase['image']     = $postData['image'];
            $purchase['provider']  = $postData['provider'];
            $purchase['status']    = 1;
            $purchase['type']      = 1;
            $purchase['request_time']   = date('Y-m-d H:i:s',time());
            if($purchase->save(false)){
                return parent::isMessage(200,'申请成功');
            }
        }
    }
   // 报废列表
    public function actionScrapList()
    {
        $uerId  = Yii::$app->user->identity->getId();
        $list   = Goods::find()->select('id,name,model,buy_time,num')->where(['pid' => $uerId])->andFilterWhere(['<>','num',0])->asArray()->all();

        if($list){
            foreach ($list as $k=>$v){
                if (!preg_match('/(\#)/i',$v['model'])){
                    $list[$k]['scale'] = $v['model'];
                    $list[$k]['type']  = '';
                }else{
                    $list[$k]['scale'] = strstr($v['model'],'#',true);
                    $list[$k]['type']  = ltrim(strstr($v['model'],'#',false),'#');
                }
            }
            return parent::isMessage(200,'申请成功',$list);
        }else{

            return parent::isMessage(400,'您的项目目前没有物资');
        }
    }
    //报废申请
    public function actionScrapApply()
    {
         $request = Yii::$app->request;
         $postData = $request->post();
        if(empty($postData['id'] ) || empty($postData['num'] ) || empty($postData['reason'] )|| empty($postData['salvage'] )  || empty($postData['image'] )){
            return parent::isMessage(400,'参数不能为空');
        }else{
            $data = new Check();
            $postDatas = Goods::findOne(['id' => $postData['id']]);
            unset($postDatas['id']);
            $data['request_num'] = $postData['num'];
            $data['gid']        = $postData['id'];
            $data['reason']     = $postData['reason'];
            $data['salvage']    = $postData['salvage'];
            $data['image']      = $postData['image'];

            $data['model']      = $postDatas['model'];
            $data['provider']   = $postDatas['provider'];
            $data['unit']       = $postDatas['unit'];
            $data['name']       = $postDatas['name'];
            $data['pid']        = $postDatas['pid'];
            $data['buy_time']   = $postDatas['buy_time'];
            $data['price']      = $postDatas['price'];
            $data['request_time']  = date('Y-m-d H:i:s',time());
            $data['status']     = 1;
            $data['type']       = 3;
            $data['all_price']  = $postDatas['price']*$postData['num'];
            if($data->save(false)){
                return parent::isMessage(200,'添加成功');
            }else{
                return parent::isMessage(400,'添加失败');
            }
        }
    }

    //我的 模块
    public function actionMine()
    {
        $datas['id'] = Yii::$app->user->identity->getId();
        $userInfo   = AdminUser::findOne(['id'=>$datas['id']]);
        $datas['username']     =  $userInfo['username'];
        $datas['project_name'] =  $userInfo['project_name'];
        $datas['leader']       =  $userInfo['leader'];

        return parent::isMessage(200,'添加成功',$datas);
    }

    //我的项目
    public function actionMyProject()
    {
        $id = Yii::$app->user->identity->getId();
        $myGoods = Goods::find()->select('id,name,model,buy_time,num,use_num')->where(['pid' => $id])->andFilterWhere(['<>','num',0])->asArray()->all();
        if($myGoods){
            foreach ($myGoods as $k=>$v){
                if (!preg_match('/(\#)/i',$v['model'])){
                    $myGoods[$k]['scale'] = $v['model'];
                    $myGoods[$k]['type']  = '';
                }else{
                    $myGoods[$k]['scale'] = strstr($v['model'],'#',true);
                    $myGoods[$k]['type']  = ltrim(strstr($v['model'],'#',false),'#');
                }
            }
            return parent::isMessage(200,'查询成功',$myGoods);
        }else{
            return parent::isMessage(400,'暂无物资');
        }
    }
    //  修改使用数量
    public function actionNum()
    {
        $postData = Yii::$app->request->post();
        if(empty($postData['id']) || empty($postData['use_num'] )){
            return parent::isMessage(400,'参数错误');
        }else{
            $ret = Goods::updateAll(['use_num' => $postData['use_num'] ], ['id' => $postData['id']]);
            if( $ret ){
                return parent::isMessage(200,'修改成功');
            }else{
                return parent::isMessage(400,'添加');
            }
        }
    }

    //  消息列表
    public function actionMsgList()
    {
        $id = Yii::$app->user->identity->getId();
        $message = Message::find()->select('id,content,ctime,is_pass,pid,cid')->where(['pid'=>$id])->asArray()->all();
        if($message){
            return parent::isMessage(200,'查询成功',$message);
        }else{
            return parent::isMessage(400,'暂无数据');
        }
    }
    //项目负责人审核通过
    public function actionMsgPass()
    {
        $postData = Yii::$app->request->post();//获取用户提交数据
        if(empty($postData['id']) || empty($postData['cid'])){
            return parent::isMessage(400,'参数不能为空');
        }else{
            $tr = Yii::$app->db->beginTransaction();  //开启事务
            try {
                Check::updateAll(['status' => 1],['id' => $postData['cid']]);
                $check   = Check::find()->select('pid,request_num,name,unit')->where(['id' => $postData['cid']])->one();
                $project = AdminUser::find()->select('project_name')->where(['id' => $check['pid']])->one();
                $content = '您已通过'.$project['project_name'].'调用'.$check['request_num'].$check['unit'].$check['name'].'的申请';
                $data = [
                    'content' => $content,
                    'is_pass' => 2
                ];
                Message::updateAll($data,['cid' => $postData['cid']]);
                $tr->commit();
            }catch (Exception $e) {
                //回滚
                $tr->rollBack();
                echo  "rollback";
            }
            return parent::isMessage(200,'您已同意对方请求');
        }
    }

    //项目负责人审核拒绝
    public function actionMsgVeto()
    {
        $postData = Yii::$app->request->post();//获取用户提交数据
        if(empty($postData['id']) || empty($postData['cid'])){
            return parent::isMessage(400,'参数不能为空');
        }else{
            $tr = Yii::$app->db->beginTransaction();  //开启事务
            try {
                Check::updateAll(['status' => 3],['id' => $postData['cid']]);
                $check   = Check::find()->select('pid,request_num,name,unit')->where(['id' => $postData['cid']])->one();
                $project = AdminUser::find()->select('project_name')->where(['id' => $check['pid']])->one();
                $content = '您已拒绝'.$project['project_name'].'调用'.$check['request_num'].$check['unit'].$check['name'].'的申请';
                $data = [
                    'content' => $content,
                    'is_pass' => 3
                ];
                Message::updateAll($data,['cid' => $postData['cid']]);
                $message = new Message();
                $message['pid']     = $check['pid'];
                $message['content'] = '您的审核调用'.$check['request_num'].$check['unit'].$check['name'].'的申请已被拒绝';
                $message['is_pass'] = 3;
                $message['ctime']   = date('Y-m-d H:i:s',time());
                $message->save(false);
                $tr->commit();
            }catch (Exception $e) {
                //回滚
                $tr->rollBack();
                echo  "rollback";
            }
            return parent::isMessage(200,'您已拒绝对方请求');
        }
    }

    //物资调拨列表
    public function actionAllocateList()
    {
        $id       = Yii::$app->user->identity->getId();
        $request  = Yii::$app->request;
        $name     = $request->post('name','');
        $goods = Goods::find()->select('id,pid,name,model,buy_time,num,use_num')->where(['<>', 'pid', $id])
            ->andFilterWhere(['like', 'name', $name])
            ->asArray()
            ->all();
        if($goods){
            foreach ($goods as $k=>$v){
                if (!preg_match('/(\#)/i',$v['model'])){
                    $goods[$k]['scale'] = $v['model'];
                    $goods[$k]['type']  = '';
                }else{
                    $goods[$k]['scale'] = strstr($v['model'],'#',true);
                    $goods[$k]['type']  = ltrim(strstr($v['model'],'#',false),'#');
                }
            }
            return parent::isMessage(200,'列表查询成功',$goods);
        }else{
            return parent::isMessage(400,'暂无物资');
        }
    }

    //物资调拨提交
    public function actionAllocateApply()
    {
        $postData = Yii::$app->request->post();
        $id       = Yii::$app->user->identity->getId();
        if(empty($postData['id']) || empty($postData['pid']) || empty($postData['num']) || empty($postData['use_time'])){
            return parent::isMessage(400,'参数错误');
        }else{
            $tr = Yii::$app->db->beginTransaction();  //开启事务
            try {
                $check = new Check();
                $goods = Goods::findOne(['id' => $postData['id']]);
                $check['pid']            = $id;
                $check['name']           = $goods['name'];
                $check['type']           = 2;
                $check['model']          = $goods['model'];
                $check['request_time']   = date('Y-m-d H:i:s',time());
                $check['request_num']    = $postData['num'];
                $check['recipient']      = $goods['recipient'];
                $check['provider']       = $goods['provider'];
                $check['unit']           = $goods['unit'];
                $check['image']          = $goods['image'];
                $check['status']         = 4;
                $check['buy_time']       = $goods['buy_time'];
                $check['price']          = $goods['price'];
                $check['all_price']      = $goods['price']*$postData['num'];
                $check['gid']            = $postData['id'];
                $check['bid']            = $goods['pid'] ;
                $check['use_time']       = $postData['use_time'];
                if( $check->save(false)){
                    $cid = $check->attributes['id'];
                    $message = new Message();
                    $bName = AdminUser::find()->select('project_name')->where(['id'=> $id])->one(); // 调用人
                    $message['pid']     =  $goods['pid'];
                    $message['content'] = '您是否同意'.$bName['project_name'].'调用您'.$postData['num'].$goods['unit'].$goods['name'].'?';
                    $message['cid']     = $cid;
                    $message['is_pass'] = 1;
                    $message['ctime']   = date('Y-m-d H:i:s',time());
                    $message->save(false);
                }

                $tr->commit();
            }catch (Exception $e) {
                //回滚
                $tr->rollBack();
                echo  "rollback";
            }
            return parent::isMessage(200,'调用申请成功');
        }
    }



}
